package org.zjx.swing.font;


import org.zjx.swing.bean.ParagraphBean;
import org.zjx.swing.bean.WordBean;
import org.zjx.swing.bean.Font;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;

public class WordOperate {
    public List<List<WordBean>> wordLists;
    public IFontXml iFontXml;
    public int row = 0,col = -1;

    public WordOperate(List<List<WordBean>> wordLists,IFontXml iFontXml) {
        this.wordLists = wordLists;
        this.iFontXml = iFontXml;
    }


    private WordBean getWordBean(int row,int col) throws Exception {
        if (row<0 || row > wordLists.size() - 1)
            throw new Exception("行数错误");
        List<WordBean> list = wordLists.get(row);
        if (col<0 || col > list.size() - 1)
            throw new Exception("位数错误");
        return list.get(col);
    }


    // 获取下一个单词
    public WordBean getNextWord() throws Exception {
        if (wordLists == null || wordLists.isEmpty()) {
            throw new Exception("数据为空!");
        }

        // 检查是否当前行有更多的单词
        if (col < wordLists.get(row).size() - 1) {
            col++; // 如果当前行不是最后一列，直接向右移动
        } else {
            // 如果当前行已经是最后一列，移动到下一行
            if (row < wordLists.size() - 1) {
                row++;
                col = 0; // 重置列索引为0
            } else {
                throw new Exception("没有更多数据了!");
            }
        }

        return wordLists.get(row).get(col); // 返回当前单词
    }

    // 获取上一个单词
    public WordBean getPrevWord() throws Exception {
        if (wordLists == null || wordLists.isEmpty()) {
            throw new Exception("数据为空!");
        }

        // 检查是否当前列有上一个单词
        if (col > 0) {
            col--; // 如果当前列不是第一列，直接向左移动
        } else {
            // 如果当前列已经是第一列，移动到上一行
            if (row > 0) {
                row--;
                col = wordLists.get(row).size() - 1; // 重置列索引为上一行的最后一列
            } else {
                throw new Exception("数据到顶了!");
            }
        }

        return wordLists.get(row).get(col); // 返回当前单词
    }


    public WordBean merge(int size) throws Exception {
        if (col + size > wordLists.get(row).size() - 1){
            throw new Exception("合并数量超出当前行边界,合并失败");
        }
        WordBean wordBean = null;
        for (int i = col; i <= col + size; i++) {
            if (i == col) wordBean = getWordBean(row,col);
            else wordBean = LiterateUtil.mergeWord(wordBean,getWordBean(row,i));
        }
        return wordBean;
    }


    //自动识别图片指定颜色内容，并分段 注意：必须字库全有，不然报错
    public ParagraphBean.Categories identify(String name, List<Color> colors, BufferedImage image, List<Font> fonts, int wordHeight) throws Exception {
        return FontUtil.categories(name, colors, image, fonts, wordHeight);
    }
}
